package com.exposit.books.web;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.exposit.books.domain.Order;
import com.exposit.books.service.OrderService;

@Controller
@RequestMapping("/admin")
public class AdminAcceptOrdersController {
	
	@Autowired
	private OrderService orderService;
	
	@RequestMapping(value = "/aneworders", method = RequestMethod.GET)
	public String aneworders(Model model) {

		List<Order> listOrder = orderService.getAll();
		List<Order> listNewOrder = new ArrayList<Order>();
		for (int i = 0; i < listOrder.size(); i++) {
			if (listOrder.get(i).getStatus() == 1
					|| listOrder.get(i).getStatus() == -1) {
				listNewOrder.add(listOrder.get(i));
			}
		}

		model.addAttribute("newOrders", listNewOrder);
		return "administrator/acceptorders/aneworders";
	}

	@RequestMapping(value = "/accept/{id}", method = RequestMethod.GET)
	public String accept(@PathVariable(value = "id") Long id, Model model) {

		Order order = orderService.getOrderByID(id);
		String status = "";
		
		if (order.getStatus() == 1) {
			order.setStatus(0L);
			status = "COMPLETED";
		} else if (order.getStatus() == -1) {
			order.setStatus(-2L);
			status = "SENT TO THE PUBLISHER";
		}
		orderService.updateOrder(order);

		List<Order> listOrder = orderService.getAll();
		List<Order> listNewOrder = new ArrayList<Order>();
		for (int i = 0; i < listOrder.size(); i++) {
			if (listOrder.get(i).getStatus() == 1
					|| listOrder.get(i).getStatus() == -1) {
				listNewOrder.add(listOrder.get(i));
			}
		}
		model.addAttribute("status", status);
		model.addAttribute("newOrders", listNewOrder);
		return "administrator/acceptorders/aneworders";
	}


}
